/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.controller

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.ecarx.eas.sdk.ECarXApiClient
import com.ecarx.eas.sdk.common.vr.voice.IVoiceStateListener
import com.ecarx.sdk.eas.vr.internal.voice.VoiceInfoListener
import com.ecarx.sdk.eas.vr.internal.voice.api.VrVoiceAPI
import com.ecarx.systemui.plugin.utils.LogUtils

class VoiceController : VoiceInfoListener {

    companion object {
        private const val TAG = "VoiceController"
    }

    private var mContext: Context? = null
    private var mVoiceAPI: VrVoiceAPI? = null
    private var mVrStatusListener: VrStatusListener? = null

    constructor(context: Context) {
        mContext = context
    }

    fun init(vrStatusListener: VrStatusListener) {
        mVrStatusListener = vrStatusListener
        val vrVoiceAPI = VrVoiceAPI.get()
        LogUtils.d(TAG, "init() start")
        vrVoiceAPI.init(mContext, object : ECarXApiClient.Callback {
            override fun onAPIReady(ready: Boolean) {
                LogUtils.d(TAG, "onAPIReady() start" + ready)
                if (ready) {
                    vrVoiceAPI.registerVoiceInfoListener(this@VoiceController)
                }
            }
        })
        Handler(Looper.getMainLooper()).postDelayed(Runnable {
           var success= vrVoiceAPI.registerVoiceInfoListener(this@VoiceController)
            LogUtils.d(TAG, "registerVoiceInfoListener =" + success)
        },5000)
//        LogUtils.d(TAG, "registerVoiceInfoListener start")
//        var success = vrVoiceAPI.registerVoiceInfoListener(this@VoiceController)
//        LogUtils.d(TAG, "registerVoiceInfoListener=" + success)

        mVoiceAPI = vrVoiceAPI
    }

    fun release() {
        mVoiceAPI?.unregisterVoiceInfoListener(this)
        mVrStatusListener = null
    }

    override fun onVrState(state: Int, info: String?) {
        LogUtils.d(TAG, "onVrState() called with: state = $state, info = $info")
        mVrStatusListener?.onVrState(state, info)
    }

    override fun onSemanticResult(p0: String?, p1: Int, p2: Boolean, p3: String?) {
        // do nothing
    }

    override fun onTtsState(p0: Int, p1: String?) {
        // do nothing
    }

    override fun onWakeUpMsg(p0: Int, p1: String?, p2: Int) {
        // do nothing
    }

    override fun onWakeUpMsg(p0: Int, p1: String?, p2: Int, p3: String?) {
        // do nothing
    }

    interface VrStatusListener {
        fun onVrState(state: Int, info: String?)
    }

    fun sessionStop() {
        LogUtils.d(TAG, "sessionStop")
        mVoiceAPI?.sessionStop()
    }

}